﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Criterion;

namespace ShopSpace.Core.Repositories.Impl
{
	internal class ProjectRepository : RepositoryBase<Project>, IProjectRepository
	{
		public IList<Project> ListVisibleToPerson(Person person)
		{
			DetachedCriteria inProjectPersons = DetachedCriteria.For<ProjectPerson>();
			inProjectPersons.CreateCriteria("Project").SetProjection(Projections.Property("Id"));
			inProjectPersons.Add(Expression.Eq("Person.Id", person.Id));

			DetachedCriteria criteria = DetachedCriteria.For<Project>();
			criteria.Add(Subqueries.PropertyIn("Id", inProjectPersons));
			criteria.AddOrder(Order.Asc("Name"));
			return this.GenericDAO.ListbyCriteria<Project>(criteria);

			//// When NHibernate.Linq catches up....
			//var sub = from pp in this.GenericDAO.AsQueryable<ProjectPerson>()
			//                   where pp.Person.Id == person.Id
			//                   select pp.Project.Id;
			//var query = from p in this.GenericDAO.AsQueryable<Project>()
			//            where  sub.Contains(p.Id)
			//            orderby p.Name
			//            select p;
			//return query.ToList<Project>();
		}

		public IList<Project> ListByPortal(int portalId)
		{
			var query = from p in this.GenericDAO.AsQueryable<Project>()
						where p.PortalId == portalId
						orderby p.Name
						select p;
			return query.ToList<Project>();
		}
	}
}